import React, { PureComponent } from 'react';
import { Input } from 'antd';
import {
    SearchOutlined
} from '@ant-design/icons';
import './index.scss';
import { Swiper, SwiperSlide } from 'swiper/react';
//自动轮播的按需加载
import SwiperCore, { Autoplay, Pagination } from 'swiper';
// Import Swiper styles
import 'swiper/swiper.scss';
import 'swiper/components/pagination/pagination.scss';
//使用  autoplay  pagination

import PropTypes from 'prop-types'

import debounce from 'lodash/debounce'
//如果push不能使用，引入withrouter高阶组件
import { withRouter } from 'react-router-dom'
import 'swiper/swiper.scss';
import 'swiper/components/pagination/pagination.scss';
import axios from 'axios';
import MyDrawer from './MyDrawer';

SwiperCore.use([Autoplay, Pagination])

class Header extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            swiperBg: 0,//要显示的背景的下标
            visible:false,//抽屉的显示或隐藏
            fixType:false,//头部的固定定位 false 不是固定定位  ；true  是固定定位
            mySwiper:null,//保存 swiper对象
            searchKeyList:[],//关键词
            keyword:"",//搜索的关键词
            searchList:[],//搜索的关键词形成的关键词列表
            showType:true //表示是否显示 关键词
        }
        this.getSearchData = debounce(this.getSearchData,2000)
    }

    showDrawer = () =>{
        this.setState({visible:true})
    }
    onClose = () =>{
        console.log("关闭抽屉");
    }
    componentDidMount(){
       document.addEventListener('touchmove',function(event){
           event.preventDefault();}
           ,{passive:false});
           this.onScroll();
        axios.post('/appapi/root-ceo-commodity/commodityApi/searchWords', {
            channelId: null,
            isWholeSale: 0
        }).then(res=>{
            this.setState({searchKeyList:res.data.data.keywords})
            console.log(res);
        })
    }
    componentWillUnmount(){
        window.onscroll=undefined
    }
    changeKeyword = (ev) => {
        const key = ev.target.value;
        this.setState({ keyword: key });
        if (key === "") {
            return;
        }
        this.getSearchData();

    }
    getSearchData = () =>{
        axios.post("/appapi/root-ceo-commodity/esApi/suggestion", {
            channelId: "C06022632001",
            isWholeSale: 0,
            key: this.state.keyword
        }).then(res => {
            console.log(res);
            const data = (res.data.data!==null?res.data.data.suggestionList:[])
            if (data.length > 0) {//已经搜索到数据
                this.setState({
                    searchList: data,
                    showType: false
                })
            } else {
                this.setState({
                    showType: true
                })
            }
        })
    }
    
    onScroll = () =>{
        window.onscroll=()=>{
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if(scrollTop>0){
                this.setState({fixType:true})
            }
            else{
                this.setState({fixType:false})
            }
            if(scrollTop>200){
                this.state.mySwiper.autoplay.stop()
            }
            else{
                this.state.mySwiper.autoplay.start()
            }
        }
    }
    changeDrawerType=()=>{
        this.setState({visible:false})
    }
    goList = (keyword) => {
        this.setState({ keyword: keyword });
        //页面跳转
        console.log(this.props);
        //将搜索历史保存到localstroge
        this.saveLocalStorage(keyword)
        //push 跳转 ，state传参：
        //有两个参数  ，1：路径 ，2： 可选 ，state的数据值
        this.props.history.push("/list", { keyword: keyword });
    }

    saveLocalStorage = (keyword) =>{
          const data = localStorage.getItem("search")
          console.log(data);
          if(data === null){
              localStorage.setItem("search",JSON.stringify([keyword]))
          }else{
              console.log(typeof data);
              var dataArr = JSON.parse(data);
              dataArr.unshift(keyword);
              localStorage.setItem("search",JSON.stringify(dataArr))
          }
    }

    render() {
        const { swiperList } = this.props;
        const { swiperBg, visible, fixType, searchKeyList, keyword, searchList, showType } = this.state;
        // console.log(this.props);
        // console.log(swiperList,swiperBg);
        return (<>
           <div className="main_con" style={{ background: `url('${swiperList[swiperBg].singleBackgroundURL}') top /cover`}}>
                <div className="main_title" style={fixType?{ background: `url('${swiperList[swiperBg].singleBackgroundURL}') center center /cover`,position:'fixed',display:''}:
            { background: `url('${swiperList[swiperBg].singleBackgroundURL}') center center /cover`,display:'none'}}></div>
            <span className="main_text">旺仔旺铺</span>
                <div onClick={this.showDrawer}><Input placeholder="虫虫乐园" prefix={<SearchOutlined />} className="main_h_input" /></div>
                <div className="main_swiper">
                    <Swiper
                        onSlideChange={(swiper) => {
                            //  console.log('slide change');
                            //  console.log(swiper.realIndex);
                            this.setState({ swiperBg: swiper.realIndex })
                        }}
                        onSwiper={(swiper) => {console.log(swiper);
                        this.setState({mySwiper: swiper})}}
                        autoplay={{ delay: 2000 }}   // 自动轮播
                        pagination={{ clickable: true }}  //分页
                        loop={true}  //首尾衔接的轮播
                    >
                        {
                            swiperList.map((item, index) => <SwiperSlide key={index}><img src={item.pictureURL}
                                alt={item.name} /></SwiperSlide>)
                        }
                    </Swiper>
                    </div>
                    <MyDrawer visible={visible} keyword={keyword} showType={showType}
                    searchKeyList = {searchKeyList} searchList={searchList} changeKeyword={this.changeKeyword}
                    changeDrawerType={this.changeDrawerType} goList={this.goList}></MyDrawer>
                          
            </div>
        </>);
    }
}

Header.propTypes = {
    swiperList: PropTypes.array.isRequired
}


export default withRouter(Header);